package com.winai.launcher.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.Gson;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.base.BaseRecAdapter;
import com.winai.launcher.base.BaseRecViewHolder;
import com.winai.launcher.bean.db.AlarmClockBean;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.override.LazyFragmentPagerAdapter;
import com.winai.launcher.override.dialog_global.GlobalDialog;
import com.winai.launcher.utils.AlarmManagerUtil;
import com.winai.launcher.view.timeManager.AddClockActivity;

import org.litepal.LitePal;
import org.litepal.crud.callback.FindMultiCallback;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2019/12/12 0012
 * 说明：闹钟——fragment
 */
public class AlarmClockFragment extends Fragment implements LazyFragmentPagerAdapter.Laziable {
    private Context mContext;

    @BindView(R.id.pb_loading)
    ProgressBar pbLoading;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.iv_edit)
    ImageView ivEdit;
    @BindView(R.id.iv_complete)
    ImageView ivComplete;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    @BindView(R.id.str_title)
    TextView strTitle;

    private AlarmClockAdapter alarmClockAdapter;
    private boolean editEnable = false;//可编辑模式
    private GlobalDialog.Builder tipDialog;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_alarm_clock, container, false);
        ButterKnife.bind(this, inflate);
        start();
        return inflate;
    }

    private void start() {
        initObject();
        initListener();
        requestData();
    }

    private void initObject() {
        strTitle.setText("闹钟");

        alarmClockAdapter = new AlarmClockAdapter();
        LRecyclerViewAdapter lRecyclerViewAdapter = new LRecyclerViewAdapter(alarmClockAdapter);
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 1));
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadMoreEnabled(false);

        tipDialog = new GlobalDialog.Builder(mContext)
                .setContent("确定删除闹钟吗？")
                .setTitle("提示")
                .setConfirmText("确定")
                .setCancelText("取消");
    }

    private void initListener() {
        GlobalPublisher.setListener(GlobalPublisher.ANY, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                switch (what) {
                    case GlobalPublisher.CHANGE_ALARM_CLOCK:
                        requestData();
                        break;
                    case GlobalPublisher.CLOSE_ALARM_UI:
                        //只响一次的闹钟，响铃完毕后删除Item
                        for (int i = 0; i < alarmClockAdapter.getData().size(); i++) {
                            AlarmClockBean bean = alarmClockAdapter.getData().get(i);
                            if (bean.getId().equals(String.valueOf(arg1))) {
                                //删除UI
                                alarmClockAdapter.getData().remove(i);
                                int finalI = i;
                                new Handler(Looper.getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        alarmClockAdapter.notifyItemRemoved(finalI);
                                        alarmClockAdapter.notifyItemRangeChanged(finalI
                                                , alarmClockAdapter.getData().size() - finalI);
                                    }
                                });
                                break;
                            }
                        }
                        break;
                }
            }
        });
    }

    private void requestData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                LitePal.findAllAsync(AlarmClockBean.class).listen(new FindMultiCallback<AlarmClockBean>() {
                    @Override
                    public void onFinish(List<AlarmClockBean> alarmClockBeanList) {
                        if (alarmClockBeanList == null || alarmClockBeanList.size() == 0) {
                            tvEmpty.setVisibility(View.VISIBLE);
                            editEnable = false;
                            ivEdit.setVisibility(View.GONE);
                            ivComplete.setVisibility(View.GONE);
                        } else {
                            ivEdit.setVisibility(View.VISIBLE);
                            tvEmpty.setVisibility(View.GONE);
                        }
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                hidingProgressBar();
                                alarmClockAdapter.refreshData(alarmClockBeanList);
                            }
                        });
                    }
                });
            }
        }).start();
    }

    public void showProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                pbLoading.setVisibility(View.VISIBLE);
            }
        });
    }

    public void hidingProgressBar() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                pbLoading.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 说明：切换是否编辑模式
     */
    private void toggleModel(boolean editEnable) {
        this.editEnable = editEnable;
        ivComplete.setVisibility(editEnable ? View.VISIBLE : View.GONE);
        ivEdit.setVisibility(editEnable ? View.GONE : View.VISIBLE);
        requestData();
    }


    @OnClick({R.id.iv_back, R.id.iv_home, R.id.iv_add, R.id.iv_edit, R.id.iv_complete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ((BaseActivity) mContext).finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.iv_add:
                ((BaseActivity) mContext).startActivity(new Intent(mContext, AddClockActivity.class));
                break;
            case R.id.iv_edit:
                toggleModel(true);
                break;
            case R.id.iv_complete:
                toggleModel(false);
                break;
        }
    }

    /**
     * 作者：康少
     * 时间：2019/12/16 0016
     * 说明：闹钟Item——适配器
     */
    private class AlarmClockAdapter extends BaseRecAdapter<AlarmClockBean, AlarmClockAdapter.ViewHolder> {
        @Override
        public void onHolder(ViewHolder holder, AlarmClockBean bean, int position) {
            TextView tvAmOrPm = holder.getView(R.id.tv_amOrPm);
            TextView tvDay = holder.getView(R.id.tv_day);
            TextView tvWeek = holder.getView(R.id.tv_week);
            TextView tvTime = holder.getView(R.id.tv_time);
            TextView tvRemark = holder.getView(R.id.tv_remark);
            TextView tvDelete = holder.getView(R.id.tv_delete);
            Switch switchOpen = holder.getView(R.id.switch_open);
            LinearLayout llEdit = holder.getView(R.id.ll_edit);

            /*设置特殊黑体*/
            Typeface fontFace = Typeface.createFromAsset(mContext.getAssets(), "SIMHEI.TTF");
            tvTime.setTypeface(fontFace);

            switchOpen.setVisibility(editEnable ? View.GONE : View.VISIBLE);
            llEdit.setVisibility(editEnable ? View.VISIBLE : View.GONE);
            tvTime.setText(!TextUtils.isEmpty(bean.getTime()) ? bean.getTime().substring(0, 5) : "");
            tvWeek.setText(bean.getWeek());
            tvDay.setText(bean.getDay());
            tvDay.setVisibility((bean.getWeek().equals("永不")) ? View.VISIBLE : View.GONE);
            tvRemark.setText(bean.getRemark());
            String[] split = bean.getTime().split(":");
            if (split.length >= 2) {
                String s = split[0];
                int hours = Integer.parseInt(s);
                tvAmOrPm.setText(hours > 12 ? "下午" : hours == 12 ? "中午" : "上午");
            }
            switchOpen.setOnCheckedChangeListener((buttonView, isChecked) -> {
                tvAmOrPm.setTextColor(getResources().getColor(isChecked ? R.color.colorText : R.color.colorTextGray));
                tvDay.setTextColor(getResources().getColor(isChecked ? R.color.colorText : R.color.colorTextGray));
                tvWeek.setTextColor(getResources().getColor(isChecked ? R.color.colorText : R.color.colorTextGray));
                tvTime.setTextColor(getResources().getColor(isChecked ? R.color.colorText : R.color.colorTextGray));
                tvRemark.setTextColor(getResources().getColor(isChecked ? R.color.colorText : R.color.colorTextGray));
                if (isChecked) {
                    //设置闹钟
                    AlarmManagerUtil.setAlarm(mContext, bean);
                    bean.setOpen(true);
                    bean.save();
                } else {
                    bean.setOpen(false);
                    bean.save();
                    AlarmManagerUtil.cancelAlarm(mContext, bean);
                }
            });
            switchOpen.setChecked(bean.isOpen());
            holder.itemView.setOnClickListener(v -> {
                if (editEnable) {
                    Intent intent = new Intent(mContext, AddClockActivity.class);
                    intent.putExtra("editEnable", true);
                    intent.putExtra("alarmClockBean", bean);
                    intent.putExtra("position", position);
                    startActivity(new Intent(intent));
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("editEnable", true);
//                    map.put("alarmClockBean", bean);
//                    map.put("position", position);
//                    ((BaseActivity) mContext).startAct(mContext, AddClockActivity.class, map);
                }
            });
            tvDelete.setOnClickListener(v -> {
                if (editEnable) {
                    tipDialog.setOnConfirmClickListener(new GlobalDialog.OnConfirmClickListener() {
                        @Override
                        public void onClick(GlobalDialog mGlobalDialog, View v) {
                            //删除闹钟
                            LitePal.deleteAll(AlarmClockBean.class, "alarmId = ?", bean.getId());
                            AlarmManagerUtil.cancelAlarm(mContext, bean);
                            //通知Ai删除闹钟
                            notifyReceiver(bean);
                            requestData();
                        }
                    }).show();
                }
            });
        }

        @Override
        public ViewHolder onCreateHolder() {
            return new ViewHolder(getViewByRes(R.layout.item_alarm_clock));
        }

        private class ViewHolder extends BaseRecViewHolder {
            ViewHolder(View itemView) {
                super(itemView);
            }
        }
    }

    /**
     * 说明：通知Ai删除闹钟
     */
    private void notifyReceiver(AlarmClockBean alarm) {
        String alarmJSON = new Gson().toJson(alarm);
        Intent intent = new Intent();
        intent.setAction(Constant.SpeechActionReminderRemove);
        intent.putExtra("alarmJSON", alarmJSON);
        mContext.sendBroadcast(intent);
    }
}
